package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupDao checkGroupDao;

    @Override
    public void add(Integer[] checkitemIds, CheckGroup checkGroup) {
        //添加检查组的基本信息
        checkGroupDao.add(checkGroup);
        //获取添加检查组后所生成的id值
        Integer id = checkGroup.getId();
        //调用方法添加检查项
        setCheckGroupAndCheckItem(checkitemIds, id);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<CheckGroup> page = checkGroupDao.selectByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkGroupDao.findById(id);
    }

    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {
        return checkGroupDao.findCheckItemIdsByCheckGroupId(id);
    }

    @Override
    public void edit(Integer[] checkitemIds, CheckGroup checkGroup) {
        //1.修改检查组基本信息
        checkGroupDao.edit(checkGroup);
        //2.根据id删除中间表检查组对应的所有检查项
        checkGroupDao.deleteAssocication(checkGroup.getId());
        //3.重新添加需要关联的检查项
        //获取检查组的id
        Integer id = checkGroup.getId();
        //调用方法添加检查项
        setCheckGroupAndCheckItem(checkitemIds, id);
    }

    @Override
    public void delete(Integer id) {
        //先删除对应中间表
        checkGroupDao.deleteAssocication(id);
        //删除
        checkGroupDao.delete(id);
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }

    public void setCheckGroupAndCheckItem(Integer[] checkitemIds, Integer id) {
        //判断数组是否有参数,如果没有参数则不需要关联
        if (checkitemIds != null && checkitemIds.length > 0) {
            //循环添加每个检查项与检查组的关联
            for (Integer checkitemId : checkitemIds) {
                checkGroupDao.setCheckGroupAndCheckItem(id, checkitemId);
            }
        }
    }
}
